package com.sz.callPhoneTest.call_phone_test

import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.squareup.okhttp.Request
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.StringCallback
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

class CallPhonePlugin(val context: Context) : FlutterPlugin, MethodChannel.MethodCallHandler {
    private var methodChannel: MethodChannel? = null
    private var webSocketClientEvent: WebSocketClientEvent? = null

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        EventBus.getDefault().register(this)
        methodChannel =
            MethodChannel(binding.binaryMessenger, "com.sz.callPhoneTest.call_phone_test")
        methodChannel?.setMethodCallHandler(this)

    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        EventBus.getDefault().unregister(this)
        methodChannel?.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "login" -> {
                val name = call.argument<String>("name")
                val password = call.argument<String>("password")
                Log.i("CallPhonePlugin", "login name=${name}, password=${password}")

                OkHttpUtils
                    .post()
                    .url("${Constants.SERVER_URL}/api/applogin")
                    .addParams("code", name)
                    .addParams("password", password)
                    .build()
                    .execute(object : StringCallback() {
                        override fun onError(request: Request?, e: Exception?) {
                            e?.printStackTrace()
                            result.error("404", "登陆失败", null)
                        }

                        override fun onResponse(response: String?) {
                            Log.i("CallPhonePlugin", "login response=${response}")
//                            val type = object : TypeToken<CallPhoneBaseModel<CallPhoneLoginModel>>() {}.type
//                            val model = Gson().fromJson<CallPhoneBaseModel<CallPhoneLoginModel>>(response, type)

                            val model = Gson().fromJson(response, CallPhoneBaseModel::class.java)
                            if (model.code == 0) {
                                var cid = 0
                                var code = ""

                                try{
                                    val jsonObject = JSONObject(model.data.toString())
                                    cid = jsonObject.optInt("cid")
                                    code = jsonObject.optString("code")
                                }catch (e: java.lang.Exception){
                                    e.printStackTrace()
                                }

                                Log.i("CallPhonePlugin", "cid=${cid}, code=${code}")

                                val intent = Intent(context, CallPhoneService::class.java)
                                intent.putExtra("action", 401)
                                intent.putExtra("cid", cid)
                                intent.putExtra("code", code)
                                ContextCompat.startForegroundService(context, intent)
                                result.success(200)
                            } else {
                                result.error(model.code.toString(), "登陆失败", null)
                            }
                        }

                    })

//                val intent = Intent(context, CallPhoneService::class.java)
//                intent.putExtra("action", 500)
//                intent.putExtra("cid", 1002)
//                intent.putExtra("code", "4555")
//                ContextCompat.startForegroundService(context, intent)
//                result.success(200)



            }
            "logout" -> {
                val name = call.argument<String>("name")
                Log.i("CallPhonePlugin", "name=${name}")

                OkHttpUtils
                    .post()
                    .url("${Constants.SERVER_URL}/api/apploginout")
                    .addParams("code", name)
                    .build()
                    .execute(object : StringCallback() {
                        override fun onError(request: Request?, e: Exception?) {
                            e?.printStackTrace()
                            result.error("404", "注销失败", null)
                        }

                        override fun onResponse(response: String?) {
                            Log.i("CallPhonePlugin", "logout response=${response}")
//                            val type = object : TypeToken<CallPhoneBaseModel<CallPhoneLogoutModel>>() {}.type
//                            val model = Gson().fromJson<CallPhoneBaseModel<CallPhoneLogoutModel>>(response, type)

                            val model = Gson().fromJson(response, CallPhoneBaseModel::class.java)
                            if (model.code == 0) {
                                val intent = Intent(context, CallPhoneService::class.java)
                                intent.putExtra("action", 402)
                                ContextCompat.startForegroundService(context, intent)
                                result.success(200)
                            } else {
                                result.error(model.code.toString(), "注销失败", null)
                            }
                        }

                    })
            }
            "callphone" -> {
                val intent = Intent(context, CallPhoneService::class.java)
                intent.putExtra("action", 403)
                ContextCompat.startForegroundService(context, intent)
                result.success(200)

            }
            "hangup" -> {
                val intent = Intent(context, CallPhoneService::class.java)
                intent.putExtra("action", 404)
                ContextCompat.startForegroundService(context, intent)
                result.success(200)
            }
            "startRecording" -> {
                val intent = Intent(context, CallPhoneService::class.java)
                intent.putExtra("action", 405)
                ContextCompat.startForegroundService(context, intent)
                result.success(200)

            }
            "stopRecording" -> {
                val intent = Intent(context, CallPhoneService::class.java)
                intent.putExtra("action", 406)
                ContextCompat.startForegroundService(context, intent)
                result.success(200)
            }
            "autoCLick" -> {
                val intent = Intent(context, CallPhoneService::class.java)
                intent.putExtra("action", 407)
                ContextCompat.startForegroundService(context, intent)
                result.success(200)
            }
            "getConnectState" -> {
                result.success(webSocketClientEvent?.state ?: 1)
            }
            else -> {

            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMessageEvent(event:WebSocketClientEvent) {
        webSocketClientEvent = event
        methodChannel?.invokeMethod("onWebSocketStateListener", event.state,
            object : MethodChannel.Result {
                override fun success(result: Any?) {
                    Log.i("CallPhonePlugin", "invokeMethod() -> success:${result.toString()}")
                }

                override fun error(
                    errorCode: String,
                    errorMessage: String?,
                    errorDetails: Any?
                ) {
                    Log.i("CallPhonePlugin", "invokeMethod() -> error")
                }

                override fun notImplemented() {

                }
            })

    }
}